package snakegame.src;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.Timer;

public class SnakeGame extends JFrame {

    private snakegame.src.GamePanel gamePanel;
    
    public SnakeGame() {
        setTitle("贪吃蛇游戏");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        
        gamePanel = new snakegame.src.GamePanel();
        add(gamePanel);
        
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new SnakeGame();
    }
}

class GamePanel extends JPanel implements ActionListener {

    private static final int WIDTH = 1200;
    private static final int HEIGHT = 1200;
    private static final int UNIT_SIZE = 30;
    private static final int GAME_UNITS = (WIDTH * HEIGHT) / (UNIT_SIZE * UNIT_SIZE);
    private static final int DELAY = 300;
    
    private final int[] x = new int[GAME_UNITS];
    private final int[] y = new int[GAME_UNITS];
    private int bodyParts = 3;
    private int applesEaten;
    private int appleX;
    private int appleY;
    private char direction = 'R';
    private boolean running = false;
    private Timer timer;
    private Random random;

    GamePanel() {
        random = new Random();
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(Color.black);
        setFocusable(true);
        addKeyListener(new MyKeyAdapter());
        initializeSnake();  // 新增初始化方法
        startGame();
    }

    // 新增蛇的初始化方法
    private void initializeSnake() {
        // 初始位置在画面中心向右排列
        int startX = WIDTH / 2;
        int startY = HEIGHT / 2;
        for (int i = 0; i < bodyParts; i++) {
            x[i] = startX - i * UNIT_SIZE;
            y[i] = startY;
        }
    }
    
    public void startGame() {
        newApple();
        running = true;
        timer = new Timer(DELAY, this);
        timer.start();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        draw(g);
    }

    public void draw(Graphics g) {
        if (running) {
            // 绘制苹果
            g.setColor(Color.red);
            g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);

            // 绘制蛇
            for (int i = 0; i < bodyParts; i++) {
                if (i == 0) {
                    g.setColor(Color.green);
                } else {
                    g.setColor(new Color(45, 180, 0));
                }
                g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
            }

            // 绘制分数
            g.setColor(Color.white);
            g.setFont(new Font("宋体", Font.BOLD, 40));
            FontMetrics metrics = getFontMetrics(g.getFont());
            g.drawString("得分: " + applesEaten, (WIDTH - metrics.stringWidth("得分: " + applesEaten)) / 2, g.getFont().getSize());
        } else {
            gameOver(g);
        }
    }

    public void newApple() {
        // 修正苹果生成范围计算
        int maxX = (WIDTH - UNIT_SIZE) / UNIT_SIZE;
        int maxY = (HEIGHT - UNIT_SIZE) / UNIT_SIZE;
        appleX = random.nextInt(maxX + 1) * UNIT_SIZE;
        appleY = random.nextInt(maxY + 1) * UNIT_SIZE;
    }

    public void move() {
        for (int i = bodyParts-1; i > 0; i--) {
            x[i] = x[i - 1];
            y[i] = y[i - 1];
        }

        switch (direction) {
            case 'U' : y[0] = y[0] - UNIT_SIZE;
            case 'D' : y[0] = y[0] + UNIT_SIZE;
            case 'L' : x[0] = x[0] - UNIT_SIZE;
            case 'R' : x[0] = x[0] + UNIT_SIZE;
        }
    }

    public void checkApple() {
        if ((x[0] == appleX) && (y[0] == appleY)) {
            bodyParts++;
            applesEaten++;
            newApple();
        }
    }

    public void checkCollisions() {
        // 精确边界检测（考虑蛇头尺寸）
        if (x[0] < 0 || x[0] + UNIT_SIZE > WIDTH || 
            y[0] < 0 || y[0] + UNIT_SIZE > HEIGHT) {
            running = false;
        }
        
        // 自碰检测优化（从i=4开始检测）
        for (int i = 4; i < bodyParts; i++) {
            if ((x[0] == x[i]) && (y[0] == y[i])) {
                running = false;
            }
        }
        
        if (!running) timer.stop();
    }

    public void gameOver(Graphics g) {
        // 游戏结束文字
        g.setColor(Color.red);
        g.setFont(new Font("宋体", Font.BOLD, 75));
        FontMetrics metrics = getFontMetrics(g.getFont());
        g.drawString("菜", (WIDTH - metrics.stringWidth("菜")) / 2, HEIGHT / 2);

        // 显示最终得分
        g.setColor(Color.white);
        g.setFont(new Font("宋体", Font.BOLD, 40));
        metrics = getFontMetrics(g.getFont());
        g.drawString("得分: " + applesEaten, (WIDTH - metrics.stringWidth("得分: " + applesEaten)) / 2, g.getFont().getSize());
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (running) {
            move();
            checkApple();
            checkCollisions();
        }
        repaint();
    }

    private class MyKeyAdapter extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) {
                case KeyEvent.VK_SPACE:
                    running = false;
                    initializeSnake();
                    startGame();
                    break;
                case KeyEvent.VK_LEFT:
                case KeyEvent.VK_A:
                    if (direction != 'R') direction = 'L';
                    System.out.println("左--L");
                    break;
                case KeyEvent.VK_RIGHT:
                case KeyEvent.VK_D:
                    if (direction != 'L') direction = 'R';
                    System.out.println("右--R");
                    break;
                case KeyEvent.VK_UP:
                case KeyEvent.VK_W:
                    if (direction != 'D') direction = 'U';
                    System.out.println("上--U");
                    break;
                case KeyEvent.VK_DOWN:
                case KeyEvent.VK_S:
                    if (direction != 'U') direction = 'D';
                    System.out.println("下--D");
                    break;
            }
        }
    }
}
